package com.example.imserver.service;

import com.example.imserver.entity.Message;
import com.example.imserver.repository.MessageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
public class MessageService {
    @Autowired
    private MessageRepository messageRepository;
    
    @Autowired
    private WebSocketService webSocketService;
    
    public Message sendMessage(Message message) {
        Message savedMessage = messageRepository.save(message);
        // 通过WebSocket推送消息
        webSocketService.sendMessageToUser(message.getReceiverId(), savedMessage);
        return savedMessage;
    }
    
    public List<Message> getConversation(Long userId1, Long userId2) {
        return messageRepository.findConversation(userId1, userId2);
    }
    
    public List<Message> getRecentChats(Long userId) {
        return messageRepository.findRecentChats(userId);
    }
    
    public List<Message> getUnreadMessages(Long userId) {
        return messageRepository.findUnreadMessages(userId);
    }
    
    @Transactional
    public void deleteMessage(Long messageId) {
        Message message = messageRepository.findById(messageId)
                .orElseThrow(() -> new RuntimeException("消息不存在"));
        message.setIsDeleted(true);
        messageRepository.save(message);
    }
    
    @Transactional
    public void markAsRead(Long messageId) {
        Message message = messageRepository.findById(messageId)
                .orElseThrow(() -> new RuntimeException("消息不存在"));
        message.setIsRead(true);
        messageRepository.save(message);
    }
    
    @Transactional
    public void markConversationAsRead(Long userId, Long otherUserId) {
        List<Message> messages = messageRepository.findConversation(userId, otherUserId);
        messages.forEach(msg -> {
            if (msg.getReceiverId().equals(userId) && !msg.getIsRead()) {
                msg.setIsRead(true);
                messageRepository.save(msg);
            }
        });
    }
}

